package com.yunhe.ajaxServlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.yunhe.javabean.News;
import com.yunhe.service.NewsServiceImp;

/**
 * Servlet implementation class JsonServlet
 */
@WebServlet("/JsonServlet")
public class JsonServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public JsonServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		NewsServiceImp nsi= new NewsServiceImp();
		String title1=request.getParameter("title");	
	     if(!"".equals(title1)){
			List<News> listnews=nsi.searchNews(title1);
			PrintWriter out=response.getWriter();
	/*   for(News l:listnews){
		  //String str=l.getTitle();
			  //String title="{\"title\":l.getTitle()}";
			  //String title=l.getTitle();
			 // String result="{'title':title}";
			  JSONObject result =JSONObject.fromObject(l);
			  System.out.println(result.toString());
			  out.write(result.toString());
		  }*/
			JSONArray result=JSONArray.fromObject(listnews);
			System.out.println(result.toString());
			out.write(result.toString());
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
